package handlers

import (
	"fmt"
	"github.com/emicklei/go-restful"
	"kubeInstall/model"
	"net/http"
	"strconv"
)

func GetHost(r *restful.Request, resp *restful.Response) {
	var host model.Host
	hostid := r.QueryParameter("host_id")
	if hostid == "" {
		RenderError(resp, fmt.Sprintf("get host id from http query failed!"), http.StatusBadRequest)
		return
	}
	data, err := host.Get(hostid)

	if err != nil {
		RenderError(resp, fmt.Sprintf("get host failed! error is:  %v\n", err), http.StatusBadRequest)
		return
	}

	resp.WriteHeaderAndJson(http.StatusOK, data, restful.MIME_JSON)

}

func AddHost(r *restful.Request, resp *restful.Response) {

	var req model.Host
	if err := r.ReadEntity(&req); err != nil {
		RenderError(resp, "get host failed", http.StatusInternalServerError)
		return
	}

	data, err := req.Create()

	if err != nil {
		RenderError(resp, fmt.Sprintf("add host failed %v\n", err), http.StatusBadRequest)
		return
	}

	resp.WriteHeaderAndJson(http.StatusOK, data, restful.MIME_JSON)
}

func DeleteHost(r *restful.Request, resp *restful.Response) {

	var host model.Host
	hostid := r.QueryParameter("host_id")
	if hostid == "" {
		RenderError(resp, " host id not found", http.StatusBadRequest)
		return
	}

	err := host.Delete(hostid)

	if err != nil {
		RenderError(resp, "delete host failed", http.StatusBadRequest)
		return
	}

	resp.WriteHeaderAndJson(http.StatusOK, SuccessResp{
		StatusCode: http.StatusOK,
		Message:    fmt.Sprintf("Delete %s Success ", hostid),
	}, restful.MIME_JSON)

}

func ListHost(r *restful.Request, resp *restful.Response) {

	var host model.Host

	offset, _ := strconv.Atoi(r.QueryParameter("offset"))
	limit, _ := strconv.Atoi(r.QueryParameter("limit"))

	data, err := host.List(limit, offset)

	if err != nil {
		RenderError(resp, "list host failed", http.StatusBadRequest)
		return
	}

	resp.WriteHeaderAndJson(http.StatusOK, data, restful.MIME_JSON)

}
